home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / modulefinder.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  19KB  |  699 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Find modules used by a script, using introspection.'''
  5. from __future__ import generators
  6. import dis
  7. import imp
  8. import marshal
  9. import os
  10. import sys
  11. import types
  12. import struct
  13. if hasattr(sys.__stdout__, 'newlines'):
  14.     READ_MODE = 'U'
  15. else:
  16.     READ_MODE = 'r'
  17. LOAD_CONST = chr(dis.opname.index('LOAD_CONST'))
  18. IMPORT_NAME = chr(dis.opname.index('IMPORT_NAME'))
  19. STORE_NAME = chr(dis.opname.index('STORE_NAME'))
  20. STORE_GLOBAL = chr(dis.opname.index('STORE_GLOBAL'))
  21. STORE_OPS = [
  22.     STORE_NAME,
  23.     STORE_GLOBAL]
  24. HAVE_ARGUMENT = chr(dis.HAVE_ARGUMENT)
  25. packagePathMap = { }
  26.  
  27. def AddPackagePath(packagename, path):
  28.     paths = packagePathMap.get(packagename, [])
  29.     paths.append(path)
  30.     packagePathMap[packagename] = paths
  31.  
  32. replacePackageMap = { }
  33.  
  34. def ReplacePackage(oldname, newname):
  35.     replacePackageMap[oldname] = newname
  36.  
  37.  
  38. class Module:
  39.     
  40.     def __init__(self, name, file = None, path = None):
  41.         self.__name__ = name
  42.         self.__file__ = file
  43.         self.__path__ = path
  44.         self.__code__ = None
  45.         self.globalnames = { }
  46.         self.starimports = { }
  47.  
  48.     
  49.     def __repr__(self):
  50.         s = 'Module(%r' % (self.__name__,)
  51.         if self.__file__ is not None:
  52.             s = s + ', %r' % (self.__file__,)
  53.         
  54.         if self.__path__ is not None:
  55.             s = s + ', %r' % (self.__path__,)
  56.         
  57.         s = s + ')'
  58.         return s
  59.  
  60.  
  61.  
  62. class ModuleFinder:
  63.     
  64.     def __init__(self, path = None, debug = 0, excludes = [], replace_paths = []):
  65.         if path is None:
  66.             path = sys.path
  67.         
  68.         self.path = path
  69.         self.modules = { }
  70.         self.badmodules = { }
  71.         self.debug = debug
  72.         self.indent = 0
  73.         self.excludes = excludes
  74.         self.replace_paths = replace_paths
  75.         self.processed_paths = []
  76.  
  77.     
  78.     def msg(self, level, str, *args):
  79.         if level <= self.debug:
  80.             for i in range(self.indent):
  81.                 print '   ',
  82.             
  83.             print str,
  84.             for arg in args:
  85.                 print repr(arg),
  86.             
  87.             print 
  88.         
  89.  
  90.     
  91.     def msgin(self, *args):
  92.         level = args[0]
  93.         if level <= self.debug:
  94.             self.indent = self.indent + 1
  95.             self.msg(*args)
  96.         
  97.  
  98.     
  99.     def msgout(self, *args):
  100.         level = args[0]
  101.         if level <= self.debug:
  102.             self.indent = self.indent - 1
  103.             self.msg(*args)
  104.         
  105.  
  106.     
  107.     def run_script(self, pathname):
  108.         self.msg(2, 'run_script', pathname)
  109.         fp = open(pathname, READ_MODE)
  110.         stuff = ('', 'r', imp.PY_SOURCE)
  111.         self.load_module('__main__', fp, pathname, stuff)
  112.  
  113.     
  114.     def load_file(self, pathname):
  115.         (dir, name) = os.path.split(pathname)
  116.         (name, ext) = os.path.splitext(name)
  117.         fp = open(pathname, READ_MODE)
  118.         stuff = (ext, 'r', imp.PY_SOURCE)
  119.         self.load_module(name, fp, pathname, stuff)
  120.  
  121.     
  122.     def import_hook(self, name, caller = None, fromlist = None, level = -1):
  123.         self.msg(3, 'import_hook', name, caller, fromlist, level)
  124.         parent = self.determine_parent(caller, level = level)
  125.         (q, tail) = self.find_head_package(parent, name)
  126.         m = self.load_tail(q, tail)
  127.         if not fromlist:
  128.             return q
  129.         if m.__path__:
  130.             self.ensure_fromlist(m, fromlist)
  131.         
  132.  
  133.     
  134.     def determine_parent(self, caller, level = -1):
  135.         self.msgin(4, 'determine_parent', caller, level)
  136.         if not caller or level == 0:
  137.             self.msgout(4, 'determine_parent -> None')
  138.             return None
  139.         pname = caller.__name__
  140.         if level >= 1:
  141.             if caller.__path__:
  142.                 level -= 1
  143.             
  144.             if level == 0:
  145.                 parent = self.modules[pname]
  146.                 if not parent is caller:
  147.                     raise AssertionError
  148.                 self.msgout(4, 'determine_parent ->', parent)
  149.                 return parent
  150.             if pname.count('.') < level:
  151.                 raise ImportError, 'relative importpath too deep'
  152.             pname.count('.') < level
  153.             pname = '.'.join(pname.split('.')[:-level])
  154.             parent = self.modules[pname]
  155.             self.msgout(4, 'determine_parent ->', parent)
  156.             return parent
  157.         if caller.__path__:
  158.             parent = self.modules[pname]
  159.             if not caller is parent:
  160.                 raise AssertionError
  161.             self.msgout(4, 'determine_parent ->', parent)
  162.             return parent
  163.         if '.' in pname:
  164.             i = pname.rfind('.')
  165.             pname = pname[:i]
  166.             parent = self.modules[pname]
  167.             if not parent.__name__ == pname:
  168.                 raise AssertionError
  169.             self.msgout(4, 'determine_parent ->', parent)
  170.             return parent
  171.         self.msgout(4, 'determine_parent -> None')
  172.  
  173.     
  174.     def find_head_package(self, parent, name):
  175.         self.msgin(4, 'find_head_package', parent, name)
  176.         if '.' in name:
  177.             i = name.find('.')
  178.             head = name[:i]
  179.             tail = name[i + 1:]
  180.         else:
  181.             head = name
  182.             tail = ''
  183.         if parent:
  184.             qname = '%s.%s' % (parent.__name__, head)
  185.         else:
  186.             qname = head
  187.         q = self.import_module(head, qname, parent)
  188.         if q:
  189.             self.msgout(4, 'find_head_package ->', (q, tail))
  190.             return (q, tail)
  191.         self.msgout(4, 'raise ImportError: No module named', qname)
  192.         raise ImportError, 'No module named ' + qname
  193.  
  194.     
  195.     def load_tail(self, q, tail):
  196.         self.msgin(4, 'load_tail', q, tail)
  197.         m = q
  198.         while tail:
  199.             i = tail.find('.')
  200.             if i < 0:
  201.                 i = len(tail)
  202.             
  203.             head = tail[:i]
  204.             tail = tail[i + 1:]
  205.             mname = '%s.%s' % (m.__name__, head)
  206.             m = self.import_module(head, mname, m)
  207.             if not m:
  208.                 self.msgout(4, 'raise ImportError: No module named', mname)
  209.                 raise ImportError, 'No module named ' + mname
  210.             m
  211.         self.msgout(4, 'load_tail ->', m)
  212.         return m
  213.  
  214.     
  215.     def ensure_fromlist(self, m, fromlist, recursive = 0):
  216.         self.msg(4, 'ensure_fromlist', m, fromlist, recursive)
  217.         for sub in fromlist:
  218.             if sub == '*':
  219.                 if not recursive:
  220.                     all = self.find_all_submodules(m)
  221.                     if all:
  222.                         self.ensure_fromlist(m, all, 1)
  223.                     
  224.                 
  225.             recursive
  226.             if not hasattr(m, sub):
  227.                 subname = '%s.%s' % (m.__name__, sub)
  228.                 submod = self.import_module(sub, subname, m)
  229.                 if not submod:
  230.                     raise ImportError, 'No module named ' + subname
  231.                 submod
  232.                 continue
  233.         
  234.  
  235.     
  236.     def find_all_submodules(self, m):
  237.         if not m.__path__:
  238.             return None
  239.         modules = { }
  240.         suffixes = []
  241.         for triple in imp.get_suffixes():
  242.             suffixes.append(triple[0])
  243.         
  244.         for dir in m.__path__:
  245.             
  246.             try:
  247.                 names = os.listdir(dir)
  248.             except os.error:
  249.                 m.__path__
  250.                 m.__path__
  251.                 self.msg(2, "can't list directory", dir)
  252.                 continue
  253.             except:
  254.                 m.__path__
  255.  
  256.             for name in names:
  257.                 mod = None
  258.                 for suff in suffixes:
  259.                     n = len(suff)
  260.                     if name[-n:] == suff:
  261.                         mod = name[:-n]
  262.                         break
  263.                         continue
  264.                     m.__path__
  265.                 
  266.                 if mod and mod != '__init__':
  267.                     modules[mod] = mod
  268.                     continue
  269.             
  270.         
  271.         return modules.keys()
  272.  
  273.     
  274.     def import_module(self, partname, fqname, parent):
  275.         self.msgin(3, 'import_module', partname, fqname, parent)
  276.         
  277.         try:
  278.             m = self.modules[fqname]
  279.         except KeyError:
  280.             pass
  281.  
  282.         self.msgout(3, 'import_module ->', m)
  283.         return m
  284.         if fqname in self.badmodules:
  285.             self.msgout(3, 'import_module -> None')
  286.             return None
  287.         if parent and parent.__path__ is None:
  288.             self.msgout(3, 'import_module -> None')
  289.             return None
  290.         
  291.         try:
  292.             if parent:
  293.                 pass
  294.             (fp, pathname, stuff) = self.find_module(partname, parent.__path__, parent)
  295.         except ImportError:
  296.             parent.__path__ is None
  297.             parent.__path__ is None
  298.             fqname in self.badmodules
  299.             self.msgout(3, 'import_module ->', None)
  300.             return None
  301.  
  302.         
  303.         try:
  304.             m = self.load_module(fqname, fp, pathname, stuff)
  305.         finally:
  306.             pass
  307.  
  308.         self.msgout(3, 'import_module ->', m)
  309.         return m
  310.  
  311.     
  312.     def load_module(self, fqname, fp, pathname, file_info):
  313.         (suffix, mode, type) = file_info
  314.         if fp:
  315.             pass
  316.         self.msgin(2, 'load_module', fqname, 'fp', pathname)
  317.         if type == imp.PKG_DIRECTORY:
  318.             m = self.load_package(fqname, pathname)
  319.             self.msgout(2, 'load_module ->', m)
  320.             return m
  321.         if type == imp.PY_SOURCE:
  322.             co = compile(fp.read() + '\n', pathname, 'exec')
  323.         elif type == imp.PY_COMPILED:
  324.             if fp.read(4) != imp.get_magic():
  325.                 self.msgout(2, 'raise ImportError: Bad magic number', pathname)
  326.                 raise ImportError, 'Bad magic number in %s' % pathname
  327.             fp.read(4) != imp.get_magic()
  328.             fp.read(4)
  329.             co = marshal.load(fp)
  330.         else:
  331.             co = None
  332.         m = self.add_module(fqname)
  333.         m.__file__ = pathname
  334.         if co:
  335.             if self.replace_paths:
  336.                 co = self.replace_paths_in_code(co)
  337.             
  338.             m.__code__ = co
  339.             self.scan_code(co, m)
  340.         
  341.         self.msgout(2, 'load_module ->', m)
  342.         return m
  343.  
  344.     
  345.     def _add_badmodule(self, name, caller):
  346.         if name not in self.badmodules:
  347.             self.badmodules[name] = { }
  348.         
  349.         if caller:
  350.             self.badmodules[name][caller.__name__] = 1
  351.         else:
  352.             self.badmodules[name]['-'] = 1
  353.  
  354.     
  355.     def _safe_import_hook(self, name, caller, fromlist, level = -1):
  356.         if name in self.badmodules:
  357.             self._add_badmodule(name, caller)
  358.             return None
  359.         
  360.         try:
  361.             self.import_hook(name, caller, level = level)
  362.         except ImportError:
  363.             name in self.badmodules
  364.             msg = name in self.badmodules
  365.             self.msg(2, 'ImportError:', str(msg))
  366.             self._add_badmodule(name, caller)
  367.         except:
  368.             name in self.badmodules
  369.  
  370.         if fromlist:
  371.             for sub in fromlist:
  372.                 if sub in self.badmodules:
  373.                     self._add_badmodule(sub, caller)
  374.                     continue
  375.                 
  376.                 
  377.                 try:
  378.                     self.import_hook(name, caller, [
  379.                         sub], level = level)
  380.                 continue
  381.                 except ImportError:
  382.                     msg = None
  383.                     self.msg(2, 'ImportError:', str(msg))
  384.                     fullname = name + '.' + sub
  385.                     self._add_badmodule(fullname, caller)
  386.                     continue
  387.                 
  388.  
  389.             
  390.         
  391.  
  392.     
  393.     def scan_opcodes(self, co, unpack = struct.unpack):
  394.         code = co.co_code
  395.         names = co.co_names
  396.         consts = co.co_consts
  397.         while code:
  398.             c = code[0]
  399.             if c in STORE_OPS:
  400.                 (oparg,) = unpack('<H', code[1:3])
  401.                 yield ('store', (names[oparg],))
  402.                 code = code[3:]
  403.                 continue
  404.             
  405.             if c == LOAD_CONST and code[3] == IMPORT_NAME:
  406.                 (oparg_1, oparg_2) = unpack('<xHxH', code[:6])
  407.                 yield ('import', (consts[oparg_1], names[oparg_2]))
  408.                 code = code[6:]
  409.                 continue
  410.             
  411.             if c >= HAVE_ARGUMENT:
  412.                 code = code[3:]
  413.                 continue
  414.             code = code[1:]
  415.  
  416.     
  417.     def scan_opcodes_25(self, co, unpack = struct.unpack):
  418.         code = co.co_code
  419.         names = co.co_names
  420.         consts = co.co_consts
  421.         LOAD_LOAD_AND_IMPORT = LOAD_CONST + LOAD_CONST + IMPORT_NAME
  422.         while code:
  423.             c = code[0]
  424.             if c in STORE_OPS:
  425.                 (oparg,) = unpack('<H', code[1:3])
  426.                 yield ('store', (names[oparg],))
  427.                 code = code[3:]
  428.                 continue
  429.             
  430.             if code[:9:3] == LOAD_LOAD_AND_IMPORT:
  431.                 (oparg_1, oparg_2, oparg_3) = unpack('<xHxHxH', code[:9])
  432.                 level = consts[oparg_1]
  433.                 if level == -1:
  434.                     yield ('import', (consts[oparg_2], names[oparg_3]))
  435.                 elif level == 0:
  436.                     yield ('absolute_import', (consts[oparg_2], names[oparg_3]))
  437.                 else:
  438.                     yield ('relative_import', (level, consts[oparg_2], names[oparg_3]))
  439.                 code = code[9:]
  440.                 continue
  441.             
  442.             if c >= HAVE_ARGUMENT:
  443.                 code = code[3:]
  444.                 continue
  445.             code = code[1:]
  446.  
  447.     
  448.     def scan_code(self, co, m):
  449.         code = co.co_code
  450.         if sys.version_info >= (2, 5):
  451.             scanner = self.scan_opcodes_25
  452.         else:
  453.             scanner = self.scan_opcodes
  454.         for what, args in scanner(co):
  455.             None if what == 'store' else have_star
  456.             if what == 'relative_import':
  457.                 (level, fromlist, name) = args
  458.                 if name:
  459.                     self._safe_import_hook(name, m, fromlist, level = level)
  460.                 else:
  461.                     parent = self.determine_parent(m, level = level)
  462.                     self._safe_import_hook(parent.__name__, None, fromlist, level = 0)
  463.             name
  464.             raise RuntimeError(what)
  465.         
  466.         for c in co.co_consts:
  467.             if isinstance(c, type(co)):
  468.                 self.scan_code(c, m)
  469.                 continue
  470.         
  471.  
  472.     
  473.     def load_package(self, fqname, pathname):
  474.         self.msgin(2, 'load_package', fqname, pathname)
  475.         newname = replacePackageMap.get(fqname)
  476.         if newname:
  477.             fqname = newname
  478.         
  479.         m = self.add_module(fqname)
  480.         m.__file__ = pathname
  481.         m.__path__ = [
  482.             pathname]
  483.         m.__path__ = m.__path__ + packagePathMap.get(fqname, [])
  484.         (fp, buf, stuff) = self.find_module('__init__', m.__path__)
  485.         self.load_module(fqname, fp, buf, stuff)
  486.         self.msgout(2, 'load_package ->', m)
  487.         return m
  488.  
  489.     
  490.     def add_module(self, fqname):
  491.         if fqname in self.modules:
  492.             return self.modules[fqname]
  493.         return m
  494.  
  495.     
  496.     def find_module(self, name, path, parent = None):
  497.         if parent is not None:
  498.             fullname = parent.__name__ + '.' + name
  499.         else:
  500.             fullname = name
  501.         if fullname in self.excludes:
  502.             self.msgout(3, 'find_module -> Excluded', fullname)
  503.             raise ImportError, name
  504.         fullname in self.excludes
  505.         if path is None:
  506.             if name in sys.builtin_module_names:
  507.                 return (None, None, ('', '', imp.C_BUILTIN))
  508.             path = self.path
  509.         
  510.         return imp.find_module(name, path)
  511.  
  512.     
  513.     def report(self):
  514.         '''Print a report to stdout, listing the found modules with their
  515.         paths, as well as modules that are missing, or seem to be missing.
  516.         '''
  517.         print 
  518.         print '  %-25s %s' % ('Name', 'File')
  519.         print '  %-25s %s' % ('----', '----')
  520.         keys = self.modules.keys()
  521.         keys.sort()
  522.         for key in keys:
  523.             m = self.modules[key]
  524.             if m.__path__:
  525.                 print 'P',
  526.             else:
  527.                 print 'm',
  528.             print '%-25s' % key,
  529.             if not m.__file__:
  530.                 pass
  531.             print ''
  532.         
  533.         (missing, maybe) = self.any_missing_maybe()
  534.         if missing:
  535.             print 
  536.             print 'Missing modules:'
  537.             for name in missing:
  538.                 mods = self.badmodules[name].keys()
  539.                 mods.sort()
  540.                 print '?', name, 'imported from', ', '.join(mods)
  541.             
  542.         
  543.         if maybe:
  544.             print 
  545.             print 'Submodules thay appear to be missing, but could also be', 'global names in the parent package:'
  546.             for name in maybe:
  547.                 mods = self.badmodules[name].keys()
  548.                 mods.sort()
  549.                 print '?', name, 'imported from', ', '.join(mods)
  550.             
  551.         
  552.  
  553.     
  554.     def any_missing(self):
  555.         '''Return a list of modules that appear to be missing. Use
  556.         any_missing_maybe() if you want to know which modules are
  557.         certain to be missing, and which *may* be missing.
  558.         '''
  559.         (missing, maybe) = self.any_missing_maybe()
  560.         return missing + maybe
  561.  
  562.     
  563.     def any_missing_maybe(self):
  564.         '''Return two lists, one with modules that are certainly missing
  565.         and one with modules that *may* be missing. The latter names could
  566.         either be submodules *or* just global names in the package.
  567.  
  568.         The reason it can\'t always be determined is that it\'s impossible to
  569.         tell which names are imported when "from module import *" is done
  570.         with an extension module, short of actually importing it.
  571.         '''
  572.         missing = []
  573.         maybe = []
  574.         for name in self.badmodules:
  575.             if name in self.excludes:
  576.                 continue
  577.             
  578.             i = name.rfind('.')
  579.             if i < 0:
  580.                 missing.append(name)
  581.                 continue
  582.             
  583.             subname = name[i + 1:]
  584.             pkgname = name[:i]
  585.             pkg = self.modules.get(pkgname)
  586.             if pkg is not None:
  587.                 if pkgname in self.badmodules[name]:
  588.                     missing.append(name)
  589.                 elif subname in pkg.globalnames:
  590.                     pass
  591.                 elif pkg.starimports:
  592.                     maybe.append(name)
  593.                 else:
  594.                     missing.append(name)
  595.             pkgname in self.badmodules[name]
  596.             missing.append(name)
  597.         
  598.         missing.sort()
  599.         maybe.sort()
  600.         return (missing, maybe)
  601.  
  602.     
  603.     def replace_paths_in_code(self, co):
  604.         new_filename = original_filename = os.path.normpath(co.co_filename)
  605.         for f, r in self.replace_paths:
  606.             if original_filename.startswith(f):
  607.                 new_filename = r + original_filename[len(f):]
  608.                 break
  609.                 continue
  610.         
  611.         if self.debug and original_filename not in self.processed_paths:
  612.             if new_filename != original_filename:
  613.                 self.msgout(2, 'co_filename %r changed to %r' % (original_filename, new_filename))
  614.             else:
  615.                 self.msgout(2, 'co_filename %r remains unchanged' % (original_filename,))
  616.             self.processed_paths.append(original_filename)
  617.         
  618.         consts = list(co.co_consts)
  619.         for i in range(len(consts)):
  620.             if isinstance(consts[i], type(co)):
  621.                 consts[i] = self.replace_paths_in_code(consts[i])
  622.                 continue
  623.         
  624.         return types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(consts), co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars)
  625.  
  626.  
  627.  
  628. def test():
  629.     import getopt as getopt
  630.     
  631.     try:
  632.         (opts, args) = getopt.getopt(sys.argv[1:], 'dmp:qx:')
  633.     except getopt.error:
  634.         msg = None
  635.         print msg
  636.         return None
  637.  
  638.     debug = 1
  639.     domods = 0
  640.     addpath = []
  641.     exclude = []
  642.     for o, a in opts:
  643.         if o == '-d':
  644.             debug = debug + 1
  645.         
  646.         if o == '-m':
  647.             domods = 1
  648.         
  649.         if o == '-p':
  650.             addpath = addpath + a.split(os.pathsep)
  651.         
  652.         if o == '-q':
  653.             debug = 0
  654.         
  655.         if o == '-x':
  656.             exclude.append(a)
  657.             continue
  658.     
  659.     if not args:
  660.         script = 'hello.py'
  661.     else:
  662.         script = args[0]
  663.     path = sys.path[:]
  664.     path[0] = os.path.dirname(script)
  665.     path = addpath + path
  666.     if debug > 1:
  667.         print 'path:'
  668.         for item in path:
  669.             print '   ', repr(item)
  670.         
  671.     
  672.     mf = ModuleFinder(path, debug, exclude)
  673.     for arg in args[1:]:
  674.         if arg == '-m':
  675.             domods = 1
  676.             continue
  677.         
  678.         if domods:
  679.             if arg[-2:] == '.*':
  680.                 mf.import_hook(arg[:-2], None, [
  681.                     '*'])
  682.             else:
  683.                 mf.import_hook(arg)
  684.         arg[-2:] == '.*'
  685.         mf.load_file(arg)
  686.     
  687.     mf.run_script(script)
  688.     mf.report()
  689.     return mf
  690.  
  691. if __name__ == '__main__':
  692.     
  693.     try:
  694.         mf = test()
  695.     except KeyboardInterrupt:
  696.         print '\n[interrupt]'
  697.  
  698.  
  699.